package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.gulimall.auth.feign.MemberFeignClient;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignClient;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    ThirdPartFeignClient thirdPartFeignClient;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignClient memberFeignClient;

    @ResponseBody
    @GetMapping("/wbLogin")
    public R wbLogin(@RequestParam("code") String code, HttpServletRequest request) {
        System.out.println(code);
        return R.ok();
    }

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //2. 验证码的再次校验\
        String code = null;
        String o = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (o != null) {
            long l = System.currentTimeMillis() - Long.parseLong(o.split("_")[1]);
            if (l < 60000) {
                return R.error(BizCodeEnume.VALID_SMS_CODE_EXCPTION.getMsg());
            }
        } else {
            String uuid = UUID.randomUUID().toString().substring(0,6) + "_" + System.currentTimeMillis();
            redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, uuid, 5, TimeUnit.MINUTES);
            String time = "5";
            code = uuid.split("_")[0];
            System.out.println(code);
            thirdPartFeignClient.sendSms(phone, code, time);
        }
        return R.ok();
    }

    /**
     * RedirectAttributes  请求重定向导致消息丢失,  不能用 model ,  使用 redirectAttribute  的 addFlashAttribute  方法携带数据
     * @param userRegisterVo
     * @param result
     * @param attributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegisterVo userRegisterVo, BindingResult result, RedirectAttributes attributes) {
        if (result.hasErrors()) {
            //校验出错,转发到注册页
            Map<String, String> map = new HashMap<>();
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //校验没问题, 远程注册

        //校验验证码
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
        if(s!=null &&  s.split("_")[0].equals(userRegisterVo.getCode())){
            //验证码校验通过后 //删除验证码
            redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+userRegisterVo.getPhone());
            //调用远程服务
            R r = memberFeignClient.registerMember(userRegisterVo);
            if(  r.getCode() ==0 ) {
                //注册成功
                return  "redirect:http://auth.gulimall.com/login.html";
            }else{
                //注册失败 ,  携带失败的信息
                Map<String, String> errors = new HashMap<>();
                errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            //验证码无效
            Map<String, String> errors = new HashMap<>();
            errors.put("errors","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }


    //远程登录
    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo , RedirectAttributes redirectAttributes){
        R login = memberFeignClient.login(userLoginVo);
        if(login.getCode()==0){
            return "redirect:http://gulimall.com";
        }else{
            Map<String,String> errors= new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }
}
